$(function () {
    let stepCount = 0;

    // 添加步骤
    $('#addStep').click(function () {
        const newStep = $('.step-template').clone().removeClass('d-none');
        const stepId = `step_${Date.now()}`;
        newStep.attr('id', stepId);

        // 协议切换逻辑
        newStep.find('.protocol-select').change(function () {
            const protocol = $(this).val();
            newStep.find('.protocol-configs').children().hide();
            newStep.find(`.${protocol}-config`).show();
        });

        // 删除步骤
        newStep.find('.btn-remove').click(function () {
            $(this).closest('.card').remove();
        });

        $('#stepsContainer').append(newStep);
        stepCount++;
    });

    // 提交表单
    $('#submitCase').click(function () {
        const caseData = {
            name: $('#caseName').val(),
            base_url: $('#baseProtocol').val(),
            steps: []
        };

        $('.step-template').not('.d-none').each(function () {
            const protocol = $(this).find('.protocol-select').val();
            const stepConfig = {
                protocol_type: protocol,
                name: `Step ${$(this).index() + 1}`
            };

            switch (protocol) {
                case 'http':
                    stepConfig.http_api = {
                        method: $(this).find('.method').val(),
                        path: $(this).find('.path').val()
                    };
                    break;
                case 'thrift':
                    // 补充Thrift配置字段
                    break;
                case 'sql':
                    // 补充SQL配置字段
                    break;
            }

            caseData.steps.push(stepConfig);
        });

        // 发送请求
        $.ajax({
            url: '/api/cases/create_case/',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(caseData),
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            },
            success: function (response) {
                alert('用例创建成功，ID: ' + response.id);
                window.location.href = '/cases/';
            },
            error: function (xhr) {
                alert('创建失败: ' + xhr.responseJSON.detail);
            }
        });
    });

    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});